//
//  YHComposeTextView.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/7/3.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit

class YHComposeTextView: UITextView {
    
    override var font:UIFont?{
        //通过didSet监听font改变
        didSet{
            placeholderLabel.font = font
        }
    }
    
    var placeholder:String?{
        didSet{
            placeholderLabel.text = placeholder
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        addSubview(placeholderLabel)
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self).offset(8)
            make.left.equalTo(self).offset(5)
            make.width.equalTo(SCREENW - 10)
        }
        
        //当前view贴到了textView身上，想让监听到textView中值的改变，使用代理或通知，但是代理方法已经被占用，所以我们用通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func textDidChange() {
        placeholderLabel.hidden = self.hasText()
    }
    
    private lazy var placeholderLabel:UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.grayColor()
        lab.font = UIFont.systemFontOfSize(12)
        lab.numberOfLines = 0
        return lab
    }()
}
